package com.odianyun.hello.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.odianyun.hello.model.DTO.SuZhouDTO;
import com.odianyun.hello.model.VO.SuZhouVO;
import com.odianyun.hello.service.ISuZhouService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class SuZhouServiceImpl implements ISuZhouService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public String save(SuZhouDTO suZhouDTO) {
        mongoTemplate.save(suZhouDTO);
        return "success";
    }

    @Override
    public List<SuZhouDTO> findById(SuZhouDTO suZhouDTO) {
        List<SuZhouDTO> listSuZhou = (List<SuZhouDTO>) mongoTemplate.findById(suZhouDTO,SuZhouDTO.class);
        System.out.println(JSONObject.toJSONString(listSuZhou));
        return listSuZhou;
    }

    @Override
    public List<SuZhouDTO> findAll() {
        List<SuZhouDTO> listSuZhou =mongoTemplate.findAll(SuZhouDTO.class);
        return listSuZhou;
    }

    @Override
    public List<SuZhouDTO> findWithRegex(String patternName) {
        Criteria criteria = new Criteria();
        Pattern pattern = Pattern.compile("^.*"+ patternName + ".*$" + Pattern.CASE_INSENSITIVE);
        criteria.and("name").regex(pattern);
        Query query = new Query(criteria);
        List<SuZhouDTO> list = mongoTemplate.find(query,SuZhouDTO.class);
        return list;
    }
}